//201902104030_何琛选
package cn.edu.sdjzu.xg.bysj.service;

import cn.edu.sdjzu.xg.bysj.dao.CommonDao;
import cn.edu.sdjzu.xg.bysj.dao.SchoolDao;
import cn.edu.sdjzu.xg.bysj.domain.School;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;
import util.bysjException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class SchoolService {
	private static SchoolDao schoolDao= SchoolDao.getInstance();
	private static SchoolService schoolService=new SchoolService();

	public static SchoolService getInstance(){
		return schoolService;
	}

	public Collection<School> findAll(
			List<Condition> conditions_json, Pagination pagination)
			throws SQLException {
		//获得链接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		Collection<School> schools =
				schoolDao.findAll(connection,conditions_json,pagination);
		JdbcHelper.close(connection);
		return schools;
	}
	
	public School find(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		School school = schoolDao.find(id,connection);
		JdbcHelper.close(connection);
		return school;
	}

	public boolean update(School school) throws SQLException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();
		result = schoolDao.update(school,connection);
		return result;
	}
	
	public boolean add(School school) throws SQLException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();
		result = schoolDao.add(school,connection);
		return result;
	}

	public boolean delete(Integer id) throws SQLException, bysjException {
		Connection connection = JdbcHelper.getConn();
		boolean result = false;
		School school = this.find(id);
		result = this.delete(school);
		JdbcHelper.close(connection);
		return result;
	}
	
	public boolean delete(School school) throws SQLException, bysjException {
		boolean result = false;
		Connection connection = JdbcHelper.getConn();

		int countDepartmentsOfSchool = CommonDao.getInstance().
				countWhereForeignKey(connection,"department","school_id",school.getId());
		//若没有二级单位，则能够删除
		if(countDepartmentsOfSchool==0){
			result = schoolDao.delete(school,connection);
		}else {
			throw new bysjException(school.getDescription()+"有下属系，不能删除");
		}
		JdbcHelper.close(connection);
		return result;
	}
}
